<script setup lang="ts">
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"
import {onMounted, onUnmounted, ref} from "vue";
import {getBaseURL, getToken} from "@/utils";
const emits = defineEmits<{
  (e: 'update:content', data: string): void
}>()

const props = defineProps<{
  content: string
  placeholder: string
  readonly: boolean
}>()

const aiEditor = ref<AiEditor>()

const divRef = ref();

function init (content: string) {
  aiEditor.value = new AiEditor({
    element: divRef.value as Element,
    placeholder: props.placeholder,
    draggable: false,
    content: '',
    image: {
      allowBase64: true,
      defaultSize: 350,
      uploadUrl: getBaseURL() + 'file/uploadImg',
      uploadHeaders: {
        token: getToken()
      },
      uploader: (file, _, headers) => {
        const formData = new FormData()
        formData.append('file', file)
        return fetch(getBaseURL() + 'file/uploadImg', {
          method: 'POST',
          body: formData,
          headers: headers
        }).then(res => res.json())
      },
      uploaderEvent: {
        /*onUploadBefore: (file, uploadUrl, headers) => {
          //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
        },*/
        onSuccess: (_, response) => {
          return {
            "errorCode": 0,
            "data": {
              // 图片路径
              "src": 'http://www.hbzwfw.gov.cn/competition' + response.data,
              "alt": "图片 alt"
            }
          }
        },
        /*onFailed: (file, response) => {
          //监听图片上传失败，或者返回的 json 信息不正确
        },
        onError: (file, error) => {
          //监听图片上传错误，比如网络超时等
        },*/
      }
    },
    toolbarKeys: ["undo", "redo", "brush", "eraser",
      "|", "heading", "font-family", "font-size",
      "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
      "|", "highlight", "font-color",
      "|", "align", "line-height",
      "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
      "|", "image", "video", "attachment", "quote", "code-block", "table",
      "|", "source-code", "printer", "fullscreen", /*'ai'*/
    ],
    textSelectionBubbleMenu: {
      enable: true,
      items: [/*"ai",*/ "Bold", "Italic", "Underline", "Strike", "code", "comment"],
    },
    onChange: (e) => {
      emits('update:content', e.getHtml())
    },
  }).setContent(content).setEditable(props.readonly)
}

function clear () {
  if (aiEditor.value) {
    aiEditor.value?.destroy()
  }
}

defineExpose({
  init,
  clear
})
</script>

<template>
  <div ref="divRef" style="height: 300px"></div>
</template>

<style scoped lang="scss">

</style>